<template>
  <el-form>
    <el-form-item label="题目编排：">
      <el-select v-model="value" filterable remote reserve-keyword placeholder="请输入题目ID或题目关键词"
        :remote-method="remoteMethod" :loading="loading">
        <el-option v-for="item in options" :key="item.ID" :label="item.name" :value="Number(item.ID)"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" >
import { asyncselectquestion, asyncadminselectquestion } from "../api";
import { ref, watch, defineComponent, PropType } from "vue";
import { throttle } from "underscore";
import Studycodemodel from "../mysql_interface/studycodemodel";
import { useStore } from "vuex";
import { Storekey } from "../interface";

export default defineComponent({
  props: {
    select: {
      type: Function as PropType<(v: Studycodemodel.Iquestion) => void>,
    },
  },
  setup(p) {
    const value = ref<number>();
    const loading = ref(false);
    const options = ref<Studycodemodel.Iquestion[]>([]);
    const count1 = ref(0);
    const store = useStore(Storekey);

    async function _remoteMethod(query: string) {
      if (query) {
        loading.value = true;
        const q = Number(query);
        let _like: [keyof Studycodemodel.Iquestion, any] = ["name", query];
        if (q) {
          _like = ["ID", Number(query)];
        }
        const isAdmin = location.pathname.includes("admin");

        if (isAdmin) {
          const { rows, count } = await asyncadminselectquestion({
            _like,
          });
          options.value = rows;
          count1.value = count;
          loading.value = false;
        } else {
          const { rows, count } = await asyncselectquestion({
            _like,
          });
          options.value = rows;
          count1.value = count;
          loading.value = false;
        }
      }
    }

    watch(
      () => value.value,
      () => {
        if (value.value && p.select) {
          const d = options.value.find((v) => v.ID == value.value);
          if (d) {
            p.select(d);
            value.value = undefined;
          }
        }
      }
    );

    const remoteMethod = throttle(_remoteMethod, 1000);

    return {
      value,
      loading,
      options,
      count1,
      remoteMethod,
    };
  },
});
</script>
